const db = require('../config/database')
const { success, error } = require('../utils/responseHelper')
const { getTimeDifference } = require('../utils/dateHelper')

const recordController = {
  // 开始考试
  async startExam(req, res, next) {
    try {
      const { examId } = req.params
      const userId = req.user.id

      // 检查考试是否存在且可参加
      const [exams] = await db.execute(
        `
        SELECT * FROM exams 
        WHERE id = ? AND status = 'published' 
        AND start_time <= NOW() AND end_time >= NOW()
      `,
        [examId]
      )

      if (exams.length === 0) {
        return error(res, '考试不存在或不在考试时间内', 404)
      }

      // 检查是否已经开始考试
      const [existingRecords] = await db.execute(
        'SELECT * FROM exam_records WHERE exam_id = ? AND user_id = ?',
        [examId, userId]
      )

      if (existingRecords.length > 0) {
        const record = existingRecords[0]

        // 如果已经提交，不能重新开始
        if (record.status === 'submitted') {
          return error(res, '您已经提交过该考试', 400)
        }

        // 检查是否超时
        const exam = exams[0]
        const startTime = new Date(record.start_time)
        const now = new Date()
        const elapsedMinutes = Math.floor((now - startTime) / 1000 / 60)

        if (elapsedMinutes >= exam.duration) {
          // 自动提交超时考试
          await db.execute(
            'UPDATE exam_records SET status = "timeout", end_time = NOW() WHERE id = ?',
            [record.id]
          )
          return error(res, '考试时间已结束', 400)
        }

        // 返回现有记录
        return success(res, {
          ...record,
          remaining_time: exam.duration - elapsedMinutes,
        })
      }

      // 创建新的考试记录
      const [result] = await db.execute(
        `
        INSERT INTO exam_records (exam_id, user_id, start_time, status) 
        VALUES (?, ?, NOW(), 'in_progress')
      `,
        [examId, userId]
      )

      const newRecord = {
        id: result.insertId,
        exam_id: examId,
        user_id: userId,
        start_time: new Date(),
        status: 'in_progress',
        remaining_time: exams[0].duration,
      }

      success(res, newRecord, '考试开始')
    } catch (err) {
      next(err)
    }
  },

  // 提交单个答案
  async submitAnswer(req, res, next) {
    try {
      const { recordId } = req.params
      const { question_id, answer } = req.body
      const userId = req.user.id

      // 验证考试记录
      const [records] = await db.execute(
        `
        SELECT er.*, e.duration, e.end_time
        FROM exam_records er
        JOIN exams e ON er.exam_id = e.id
        WHERE er.id = ? AND er.user_id = ? AND er.status = 'in_progress'
      `,
        [recordId, userId]
      )

      if (records.length === 0) {
        return error(res, '考试记录不存在或已结束', 404)
      }

      const record = records[0]

      // 检查考试时间
      const startTime = new Date(record.start_time)
      const now = new Date()
      const elapsedMinutes = Math.floor((now - startTime) / 1000 / 60)

      if (
        elapsedMinutes >= record.duration ||
        now > new Date(record.end_time)
      ) {
        // 自动提交超时考试
        await db.execute(
          'UPDATE exam_records SET status = "timeout", end_time = NOW() WHERE id = ?',
          [recordId]
        )
        return error(res, '考试时间已结束', 400)
      }

      // 检查题目是否属于该考试
      const [questions] = await db.execute(
        'SELECT * FROM questions WHERE id = ? AND exam_id = ?',
        [question_id, record.exam_id]
      )

      if (questions.length === 0) {
        return error(res, '题目不存在', 404)
      }

      // 保存或更新答案
      const [existingAnswers] = await db.execute(
        'SELECT id FROM answer_records WHERE record_id = ? AND question_id = ?',
        [recordId, question_id]
      )

      if (existingAnswers.length > 0) {
        // 更新现有答案
        await db.execute(
          'UPDATE answer_records SET answer = ? WHERE record_id = ? AND question_id = ?',
          [answer, recordId, question_id]
        )
      } else {
        // 插入新答案
        await db.execute(
          'INSERT INTO answer_records (record_id, question_id, answer) VALUES (?, ?, ?)',
          [recordId, question_id, answer]
        )
      }

      success(res, null, '答案保存成功')
    } catch (err) {
      next(err)
    }
  },

  // 获取已保存的答案
  async getAnswers(req, res, next) {
    try {
      const { recordId } = req.params
      const userId = req.user.id

      // 验证权限
      const [records] = await db.execute(
        'SELECT * FROM exam_records WHERE id = ? AND user_id = ?',
        [recordId, userId]
      )

      if (records.length === 0) {
        return error(res, '考试记录不存在', 404)
      }

      // 获取答案
      const [answers] = await db.execute(
        `
        SELECT ar.question_id, ar.answer, ar.score, ar.is_correct,
               q.type, q.correct_answer
        FROM answer_records ar
        JOIN questions q ON ar.question_id = q.id
        WHERE ar.record_id = ?
      `,
        [recordId]
      )

      const answerMap = {}
      answers.forEach((answer) => {
        answerMap[answer.question_id] = {
          answer: answer.answer,
          score: answer.score,
          is_correct: answer.is_correct,
          type: answer.type,
          correct_answer: answer.correct_answer,
        }
      })

      success(res, answerMap)
    } catch (err) {
      next(err)
    }
  },

  // 提交考试
  async submitExam(req, res, next) {
    try {
      const { recordId } = req.params
      const userId = req.user.id

      // 验证考试记录
      const [records] = await db.execute(
        `
        SELECT er.*, e.title as exam_title
        FROM exam_records er
        JOIN exams e ON er.exam_id = e.id
        WHERE er.id = ? AND er.user_id = ? AND er.status = 'in_progress'
      `,
        [recordId, userId]
      )

      if (records.length === 0) {
        return error(res, '考试记录不存在或已提交', 404)
      }

      const record = records[0]
      const connection = await db.getConnection()
      await connection.beginTransaction()

      try {
        // 获取所有题目和答案
        const [questionsAndAnswers] = await connection.execute(
          `
          SELECT q.*, ar.answer
          FROM questions q
          LEFT JOIN answer_records ar ON q.id = ar.question_id AND ar.record_id = ?
          WHERE q.exam_id = ?
          ORDER BY q.order_num, q.id
        `,
          [recordId, record.exam_id]
        )

        let totalScore = 0

        // 自动评分
        for (const qa of questionsAndAnswers) {
          const {
            id: questionId,
            type,
            correct_answer,
            score: questionScore,
            answer,
          } = qa

          let earnedScore = 0
          let isCorrect = false

          if (answer) {
            switch (type) {
              case 'single':
              case 'judge':
                isCorrect = answer === correct_answer
                earnedScore = isCorrect ? questionScore : 0
                break

              case 'multiple':
                // 多选题评分：完全正确才得分
                try {
                  const userAnswers = JSON.parse(answer).sort()
                  const correctAnswers = JSON.parse(correct_answer).sort()
                  isCorrect =
                    JSON.stringify(userAnswers) ===
                    JSON.stringify(correctAnswers)
                  earnedScore = isCorrect ? questionScore : 0
                } catch (e) {
                  earnedScore = 0
                }
                break

              case 'essay':
                // 简答题需要人工评分，暂时给0分
                earnedScore = 0
                break
            }

            // 更新答案记录的分数
            await connection.execute(
              'UPDATE answer_records SET score = ?, is_correct = ? WHERE record_id = ? AND question_id = ?',
              [earnedScore, isCorrect, recordId, questionId]
            )
          }

          totalScore += earnedScore
        }

        // 更新考试记录
        await connection.execute(
          'UPDATE exam_records SET status = "submitted", end_time = NOW(), total_score = ? WHERE id = ?',
          [totalScore, recordId]
        )

        await connection.commit()

        success(
          res,
          {
            total_score: totalScore,
            status: 'submitted',
          },
          '考试提交成功'
        )
      } catch (submitError) {
        await connection.rollback()
        throw submitError
      } finally {
        connection.release()
      }
    } catch (err) {
      next(err)
    }
  },

  // 获取考试记录列表（管理员用）
  async getExamRecords(req, res, next) {
    try {
      const { examId } = req.params
      const { page = 1, limit = 10, status } = req.query

      const offset = (page - 1) * limit

      let query = `
        SELECT er.*, u.username, u.name as user_name,
               TIMESTAMPDIFF(MINUTE, er.start_time, COALESCE(er.end_time, NOW())) as duration_minutes
        FROM exam_records er
        JOIN users u ON er.user_id = u.id
        WHERE er.exam_id = ?
      `

      const params = [examId]

      if (status) {
        query += ' AND er.status = ?'
        params.push(status)
      }

      query += ' ORDER BY er.created_at DESC LIMIT ? OFFSET ?'
      params.push(parseInt(limit), offset)

      const [records] = await db.execute(query, params)

      // 获取总数
      let countQuery =
        'SELECT COUNT(*) as total FROM exam_records WHERE exam_id = ?'
      const countParams = [examId]

      if (status) {
        countQuery += ' AND status = ?'
        countParams.push(status)
      }

      const [countResult] = await db.execute(countQuery, countParams)

      success(res, {
        records,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total: countResult[0].total,
          pages: Math.ceil(countResult[0].total / limit),
        },
      })
    } catch (err) {
      next(err)
    }
  },

  // 获取学生考试详情
  async getStudentExamDetail(req, res, next) {
    try {
      const { recordId } = req.params
      const userId = req.user.id

      // 获取考试记录详情
      const [records] = await db.execute(
        `
        SELECT er.*, e.title as exam_title, e.total_score as exam_total_score,
               u.name as user_name
        FROM exam_records er
        JOIN exams e ON er.exam_id = e.id
        LEFT JOIN users u ON er.user_id = u.id
        WHERE er.id = ? AND (er.user_id = ? OR ? = 'admin')
      `,
        [recordId, userId, req.user.role]
      )

      if (records.length === 0) {
        return error(res, '考试记录不存在', 404)
      }

      const record = records[0]

      // 获取题目和答案详情
      const [details] = await db.execute(
        `
        SELECT q.id, q.type, q.title, q.content, q.options, q.correct_answer, q.score,
               ar.answer, ar.score as earned_score, ar.is_correct
        FROM questions q
        LEFT JOIN answer_records ar ON q.id = ar.question_id AND ar.record_id = ?
        WHERE q.exam_id = ?
        ORDER BY q.order_num, q.id
      `,
        [recordId, record.exam_id]
      )

      // 如果是学生查看且考试未结束，不显示正确答案
      if (req.user.role === 'student' && record.status === 'in_progress') {
        details.forEach((detail) => {
          delete detail.correct_answer
          delete detail.is_correct
          delete detail.earned_score
        })
      }

      success(res, {
        record: record,
        questions: details,
      })
    } catch (err) {
      next(err)
    }
  },

  // 人工评分（简答题）
  async manualGrading(req, res, next) {
    try {
      const { recordId, questionId } = req.params
      const { score, feedback } = req.body

      // 验证题目类型
      const [questions] = await db.execute(
        'SELECT type, score as max_score FROM questions WHERE id = ?',
        [questionId]
      )

      if (questions.length === 0) {
        return error(res, '题目不存在', 404)
      }

      const question = questions[0]
      if (question.type !== 'essay') {
        return error(res, '只有简答题可以人工评分', 400)
      }

      if (score > question.max_score) {
        return error(res, '评分不能超过题目总分', 400)
      }

      const connection = await db.getConnection()
      await connection.beginTransaction()

      try {
        // 更新答案分数
        await connection.execute(
          'UPDATE answer_records SET score = ?, is_correct = ?, feedback = ? WHERE record_id = ? AND question_id = ?',
          [score, score > 0, feedback || null, recordId, questionId]
        )

        // 重新计算总分
        const [totalScoreResult] = await connection.execute(
          'SELECT SUM(score) as total FROM answer_records WHERE record_id = ?',
          [recordId]
        )

        await connection.execute(
          'UPDATE exam_records SET total_score = ? WHERE id = ?',
          [totalScoreResult[0].total || 0, recordId]
        )

        await connection.commit()
        success(res, null, '评分成功')
      } catch (gradingError) {
        await connection.rollback()
        throw gradingError
      } finally {
        connection.release()
      }
    } catch (err) {
      next(err)
    }
  },
}

module.exports = recordController
